package com.example.meitu.api.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.meitu.api.common.UserBrandsContext;
import com.example.meitu.api.common.UserContext;
import com.example.meitu.api.common.UserLoginContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hmef.attribute.MAPIAttribute;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class RequestProcessInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            //返回异常信息
            Map<String,Object> map = new HashMap<>();
            map.put("code",401);
            map.put("msg","请先登录");
            String json = JSONUtil.toJsonStr(map);
            //设置响应头（告知浏览器：响应的数据类型为json、响应的数据编码表为utf-8）
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);
            return false;//不放行
        } else {
            //直接搂下来，放到ThreadLocal中 后续直接从中获取
            UserContext context = UserLoginContextHolder.get() == null ? new UserContext() : UserLoginContextHolder.get();
            context.setToken(token);
            String result = stringRedisTemplate.opsForValue().get("user:" + token);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONUtil.parseObj(result);
                context.setUserId((Integer) jsonObject.get("userId"));
                context.setName((String) jsonObject.get("name"));
                context.setMemberShip((Integer) jsonObject.get("memberShip"));
                String paramBrands = (String) jsonObject.get("brands");
                String competitorBrands = (String) jsonObject.get("competitorBrands");
                HashMap competitorMap = JSONUtil.toBean(competitorBrands, HashMap.class);
                if (StringUtils.isNotBlank(paramBrands)) {
                    //有权限的品牌 + 竞品
                    List<Integer> permissionBrands = new ArrayList<>();
                    String[] brand = paramBrands.split(",");
                    List<UserBrandsContext> brands = new ArrayList<>();
                    for (int i = 0; i < brand.length; i++) {
                        Integer brandId = Integer.parseInt(brand[i].split("\\_",2)[0]);
                        String brandName =  brand[i].split("\\_",2)[1];
                        permissionBrands.add(brandId);
                        UserBrandsContext userBrandsContext = new UserBrandsContext(brandId, brandName);

                        String competitorStr = (String) competitorMap.get(String.valueOf(brandId));
                        String[] competitorArr = competitorStr.split(",");
                        List<Map> resultMap = new ArrayList<>();
                        for (String s : competitorArr) {
                            String competitorBrandId =  s.split("\\_",2)[0];
                            String competitorBrandName =  s.split("\\_",2)[1];
                            permissionBrands.add(Integer.parseInt(competitorBrandId));
                            Map competitorResultMap = new HashMap();
                            competitorResultMap.put("competitorBrandId",competitorBrandId);
                            competitorResultMap.put("competitorBrandName",competitorBrandName);
                            resultMap.add(competitorResultMap);
                        }
                        userBrandsContext.setCompetitor(resultMap);
                        brands.add(userBrandsContext);
                    }
                    context.setBrands(brands);
                    context.setPermissionBrands(permissionBrands);
                } else {
                    context.setBrands(new ArrayList<>());
                }
                UserLoginContextHolder.set(context);
            } else {
                //返回异常信息
                Map<String,Object> map = new HashMap<>();
                map.put("code",401);
                map.put("msg","token已失效");
                String json = JSONUtil.toJsonStr(map);
                //设置响应头（告知浏览器：响应的数据类型为json、响应的数据编码表为utf-8）
                response.setContentType("application/json;charset=utf-8");
                //响应
                response.getWriter().write(json);
                return false;//不放行
            }

        }
        //注意 这里必须是true否则请求将就此终止。
        return true;
    }
}
